import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import {
  Card,
  Button,
  Space,
  Typography,
  Tooltip,
  Input,
  Select,
  ConfigProvider
} from 'antd';
import {
  CloseOutlined,
  SearchOutlined,
  TranslationOutlined,
  BookOutlined,
  AppstoreOutlined
} from '@ant-design/icons';
import zhCN from 'antd/locale/zh_CN';
import { FloatBoxConfig } from '../types';
import { useDraggable } from '../hooks/useDraggable';
import './floatball.less';

const { Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

interface FloatBoxProps {
  onClose: () => void;
  initialConfig?: Partial<FloatBoxConfig>;
}

const FloatBox: React.FC<FloatBoxProps> = ({ onClose, initialConfig }) => {
  // 基础配置，不包含position（由hook管理）
  const baseConfig = {
    size: { width: 300, height: 400 },
    visible: true,
    pinned: false,
    ...initialConfig
  };

  const [isExpanded, setIsExpanded] = useState(false);

  // 使用自定义拖动Hook，position完全由hook管理
  const {
    elementRef: floatBallRef,
    panelRef,
    isDragging,
    currentPosition
  } = useDraggable(
    {
      position: initialConfig?.position || { x: window.innerWidth - 80, y: 200 },
      size: baseConfig.size
    },
    {
      edgeSnapThreshold: 20,
      animationDuration: 300,
      ballSize: 60
    }
  );

  const handleTogglePanel = () => {
    // Hook已经处理了拖动状态检查

    console.log('isDragging:', isDragging);
    if (isDragging) return;

    setIsExpanded(!isExpanded);
  };

  if (!baseConfig.visible) return null;

  return (
    <ConfigProvider
      locale={zhCN}
      getPopupContainer={(triggerNode) => {
        // 确保所有浮层组件都挂载到悬浮面板容器内
        return panelRef.current || document.body;
      }}
    >
      <div className="float-box-container">
        {/* 悬浮球 */}
        <div
          ref={floatBallRef}
          className={`float-ball ${isDragging ? 'dragging' : ''
            } ${isExpanded ? 'expanded' : ''
            }`}
          style={{
            position: 'fixed',
            left: currentPosition.x,
            top: currentPosition.y,
            zIndex: 10000,
            cursor: isDragging ? 'grabbing' : 'grab'
          }}
          onClick={handleTogglePanel}
        >
          <div className="float-ball-inner">
            <AppstoreOutlined style={{ fontSize: '24px', color: 'white' }} />
          </div>
        </div>

        {/* 工具面板 */}
        {isExpanded && (
          <div
            ref={panelRef}
            className="float-panel"
            style={{
              position: 'fixed',
              left: Math.max(10, currentPosition.x - baseConfig.size.width + 60),
              top: currentPosition.y,
              width: baseConfig.size.width,
              zIndex: 9999
            }}
          >
            <Card
              size="small"
              className="float-panel-card"
              title={
                <Space>
                  <AppstoreOutlined />
                  <Text strong style={{ fontSize: '14px' }}>
                    工具箱
                  </Text>
                </Space>
              }
              extra={
                <Tooltip title="关闭">
                  <Button
                    type="text"
                    size="small"
                    icon={<CloseOutlined />}
                    onClick={onClose}
                  />
                </Tooltip>
              }
            >
              <Space direction="vertical" style={{ width: '100%' }} size="small">
                <div className="tool-content">
                  <TextArea
                    placeholder="输入要翻译的文本..."
                    rows={3}
                    style={{ marginBottom: 8 }}
                  />
                  <Select
                    defaultValue="en-zh"
                    style={{ width: '100%', marginBottom: 8 }}
                    size="small"
                  >
                    <Option value="en-zh">英文 → 中文</Option>
                    <Option value="zh-en">中文 → 英文</Option>
                    <Option value="ja-zh">日文 → 中文</Option>
                    <Option value="ko-zh">韩文 → 中文</Option>
                  </Select>
                  <Button
                    type="primary"
                    size="small"
                    block
                    icon={<TranslationOutlined />}
                  >
                    翻译
                  </Button>
                </div>
              </Space>
            </Card>
          </div>
        )}
      </div>
    </ConfigProvider>
  );
};

// 创建悬浮球实例
export const createFloatBox = (config?: Partial<FloatBoxConfig>) => {
  const container = document.createElement('div');
  container.id = 'chrome-extension-float-box';
  document.body.appendChild(container);

  const root = createRoot(container);

  const handleClose = () => {
    root.unmount();
    document.body.removeChild(container);
  };

  root.render(<FloatBox onClose={handleClose} initialConfig={config} />);

  return {
    destroy: handleClose,
    container
  };
};

export default FloatBox;